package com.tongyi.lizhishop.activitys;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.bigkoo.pickerview.TimePickerView;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.tongyi.lizhishop.R;
import com.tongyi.lizhishop.api.StoreApi;
import com.tongyi.lizhishop.beans.CommonResonseBean;
import com.tongyi.lizhishop.common.BaseActivity;
import com.tongyi.lizhishop.common.CommonObserver;
import com.tongyi.lizhishop.managers.APIServiceManager;
import com.tongyi.lizhishop.utils.PromptDialogUtils;
import com.wuhenzhizao.titlebar.widget.CommonTitleBar;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import me.leefeng.promptlibrary.PromptDialog;

public class PublishRedEnvelopeActivity extends BaseActivity implements RadioGroup.OnCheckedChangeListener {

    @BindView(R.id.titlebar)
    CommonTitleBar titlebar;
    @BindView(R.id.activity_publish_red_envrep)
    LinearLayout activityPublishRedEnvrep;
    @BindView(R.id.allMoney)
    EditText allMoney;
    @BindView(R.id.condition)
    EditText condition;
    @BindView(R.id.selfGet)
    RadioButton selfGet;
    @BindView(R.id.systemPush)
    RadioButton systemPush;
    @BindView(R.id.radioGrop)
    RadioGroup radioGrop;
    @BindView(R.id.redPackCount)
    EditText redPackCount;
    @BindView(R.id.firstTimePicker)
    TextView firstTimePicker;
    @BindView(R.id.secondTimePicker)
    TextView secondTimePicker;
    @BindView(R.id.submit)
    Button submit;
    @BindView(R.id.redpackName)
    EditText redpackName;
    private TimePickerView pvTime;
    String mode = "1";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_publish_red_envrep);
        ButterKnife.bind(this);
        initTitleBarView(titlebar, "发布红包");
        initView();
    }

    private void initView() {
        radioGrop.setOnCheckedChangeListener(this);

    }

    @OnClick({R.id.firstTimePicker, R.id.secondTimePicker, R.id.submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.firstTimePicker:
                showTimePicker(firstTimePicker);
                break;
            case R.id.secondTimePicker:
                showTimePicker(secondTimePicker);
                break;
            case R.id.submit:
                if (checkParams()) {
                    submitData();
                }

                break;
        }
    }

    private void submitData() {
        submit.setEnabled(false);
        final PromptDialog promptDialog = PromptDialogUtils.getPrompDialog(this);
        promptDialog.showLoading("请等待");
        Date tag1 = (Date) firstTimePicker.getTag();
        if (tag1 == null) {
            ToastUtils.showShort("请选择开始时间");
            return;
        }
        long startTime = tag1.getTime();
        Object tag = secondTimePicker.getTag();
        if (tag == null) {
            ToastUtils.showShort("请选择结束时间");
            return;
        }
        long endTime = ((Date) tag).getTime();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String startTime_str = format.format(startTime);
        String endTime_str = format.format(endTime);
        LogUtils.w("startTime", startTime_str);
        LogUtils.w("endTime_str", endTime_str);
        String dmoney = condition.getText().toString();
        String jmoney = allMoney.getText().toString();
        String num = redPackCount.getText().toString();
        APIServiceManager.getInstance().create(StoreApi.class)
                .addCard(SPUtils.getInstance().getString("userid"),
                        redpackName.getText().toString(),
                        startTime_str,
                        endTime_str,
                        dmoney,
                        jmoney,
                        mode,
                        num
                ).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new CommonObserver<CommonResonseBean>() {
                    @Override
                    public void onSuccess(CommonResonseBean value) {
                        if ("succ".equals(value.getRe())) {

                            submit.setEnabled(true);
                            promptDialog.dismiss();
                            promptDialog.showInfo("已提交");
                            ToastUtils.showShort("请耐心等待,已提交平台审核中");
                            notifyLoadData();
                            finish();
                        } else {
                            onFailure(null);
                        }
                    }

                    @Override
                    public void onFailure(Throwable e) {
                        submit.setEnabled(true);
                        promptDialog.dismiss();
                        promptDialog.showError("提交失败,请重试");
                    }
                });

    }

    private void notifyLoadData() {
        LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent("LOADDATA"));
    }

    private boolean checkParams() {
        if (TextUtils.isEmpty(allMoney.getText().toString())
                || TextUtils.isEmpty(condition.getText().toString())
                || TextUtils.isEmpty(redPackCount.getText().toString())) {
            ToastUtils.showShort("请填写红包的基本信息");
            return false;
        }
        if (!TextUtils.isDigitsOnly(allMoney.getText().toString())
                || !TextUtils.isDigitsOnly(condition.getText().toString())
                || !TextUtils.isDigitsOnly(redPackCount.getText().toString())
                ) {
            //非数字
            ToastUtils.showShort("请准确填写数字");
            return false;
        } else {
            //数字
            if (Float.parseFloat(allMoney.getText().toString()) <= 0 || Float.parseFloat(condition.getText().toString()) < 0) {
                ToastUtils.showShort("请准确填写红包面额及使用条件");
                return false;
            }
        }
        if (!TextUtils.isDigitsOnly(redPackCount.getText().toString())) {
            ToastUtils.showShort("请准确填写红包数量");
            return false;
        }
        return true;
    }

    private void showTimePicker(final TextView tv) {
        TimePickerView.OnTimeSelectListener onTimeSelectListener = new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调yyyy-MM-dd'T'HH:mm:ss
                SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd HH时mm分");
                String time = TimeUtils.date2String(date, format);
                tv.setText(time);
                tv.setTag(date);
            }
        };
        int startYear = Calendar.getInstance().get(Calendar.YEAR);
        int month = Calendar.getInstance().get(Calendar.MONTH);
        int day = Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
        int hour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
        int minute = Calendar.getInstance().get(Calendar.MINUTE);
        LogUtils.w("time", startYear, month, day, hour, minute);
        Calendar startDate = Calendar.getInstance();
        startDate.set(startYear, month, day, hour, minute);
        Calendar endDate = Calendar.getInstance();
        endDate.set(startYear + 20, month, day, hour, minute);
        pvTime = new TimePickerView.Builder(this, onTimeSelectListener)
                .setType(new boolean[]{true, true, true, false, false, false})// 默认全部显示
                .setCancelText("取消")//取消按钮文字
                .setSubmitText("确定")//确认按钮文字
                .setContentSize(18)//滚轮文字大小
                .setTitleSize(20)//标题文字大小
                .setTitleText("请选择时间")//标题文字
                .setOutSideCancelable(true)//点击屏幕，点在控件外部范围时，是否取消显示
                .isCyclic(false)//是否循环滚动
                .setRangDate(startDate, endDate)//起始终止年月日设定
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .build();
        pvTime.show(true);
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        if (checkedId == R.id.selfGet) {
            mode = "1";
        } else if (checkedId == R.id.systemPush) {
            mode = "2";
        }
    }
}
